package com.jams.goodox.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.entity.StringBean;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.jams.goodox.widget.EditTextWithDel;
import com.jams.goodox.widget.LoadingDialog;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 找回个人密码&找回企业密码
 * true 个人 false 企业
 * Created by jams_zhen on 2017/4/27.
 */

public class FindPassFragment extends BaseFragment {
    private static final String Fragment_Param = "isFromByPerson";
    @Bind(R.id.edit_tel)
    EditTextWithDel editTel;
    @Bind(R.id.edit_verification)
    EditTextWithDel editVerification;
    @Bind(R.id.tx_send_verification)
    TextView txSendVerification;
    @Bind(R.id.tx_tel_icon)
    TextView txTelIcon;

    private boolean isFromByPerson;//true 个人 false 企业

    private View rootView;

    private String phoneNum;
    private String code;

    private static final int Time_Close = 60;//倒计时持续多少秒
    private Intent in;

    private static final String HINT_CODE_Null="请输入验证码";
    private static final String HINT_CODE_ERROR="验证码错误";
    private static final String HINT_Tel_Null_ERROR = "请输入手机号码";
    private static final String HINT_Company_Account_Null_ERROR = "请输入企业账号";
    private static final String HINT_TEL_ERROR = "请输入11位手机号";
    private static final String HINT_Company_Account_ERROR = "请输入8位企业账号";

    private LoadingDialog loadingDialog;

    public static FindPassFragment getInstance(boolean isFromByPerson) {
        FindPassFragment findPassByCompanyFragment = new FindPassFragment();
        Bundle args = new Bundle();
        args.putBoolean(Fragment_Param, isFromByPerson);
        findPassByCompanyFragment.setArguments(args);
        return findPassByCompanyFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) isFromByPerson = getArguments().getBoolean(Fragment_Param);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_find_pass_personage, container, false);
        ButterKnife.bind(this, rootView);
        init();
        return rootView;
    }

    /**
     * 此处根据个人or企业设置界面元素
     */
    private void init() {
        if (isFromByPerson){//个人
            txTelIcon.setText(R.string.phone_number);
            editTel.setHint(R.string.phone_number_hint);
            editTel.setFilters(new InputFilter[] { new InputFilter.LengthFilter(11) });
        }else {//企业
            txTelIcon.setText("企业账号：");
            editTel.setHint("请输入企业账号");
            editTel.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8) });
        }
        loadingDialog = LoadingDialog.createDialog(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tx_send_verification, R.id.tx_next})
    public void onClick(View view) {
        if(Utils.isFastDoubleClick())
            return;
        phoneNum = editTel.getText().toString().trim();
        code = editVerification.getText().toString().trim();
        switch (view.getId()) {
            case R.id.tx_send_verification:
                if (isFromByPerson) {
                    sendVerCodeByAccount();
                } else {
                    sendVerCodeByCompany();
                }
                break;
            case R.id.tx_next:
                testVerCode();
                break;
        }
    }

    /**
     * 个人账号找回密码发送验证码
     */
    private void sendVerCodeByAccount() {
        //手机长度及验证
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show(HINT_Tel_Null_ERROR);
            return;
        }
        if (!Utils.isPhoneNum(phoneNum)) {
            ToastUtil.show(HINT_TEL_ERROR);
            return;
        }
        Map<String,String> map=new HashMap<>();
        map.put("phone",phoneNum);
        map.put("type",LoginService.TYPE_FORGET_SEND_REGISTER);
        txSendVerification.setEnabled(false);
        showLoading();
        enqueue(createCallService(LoginService.class).sendCode(map), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                txSendVerification.setEnabled(true);
                doSendVerCodeSuccess();
                misLoading();
            }

            @Override
            public void onError(String msg) {
                txSendVerification.setEnabled(true);
                ToastUtil.show(msg);
                misLoading();
            }
        });
    }

    /**
     * 企业账号找回密码发送验证吗
     */
    private void sendVerCodeByCompany() {
        //企业账户长度及验证
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtil.show(HINT_Company_Account_Null_ERROR);
            return;
        }
        if (!TextUtils.isEmpty(phoneNum) && phoneNum.length() < 8) {
            ToastUtil.show(HINT_Company_Account_ERROR);
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("loginName", phoneNum);
        map.put("type", LoginService.TYPE_FORGET_SEND_REGISTER);
        txSendVerification.setEnabled(false);
        showLoading();
        enqueue(createCallService(LoginService.class).sendCompanyCode(map), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean result) {
                txSendVerification.setEnabled(true);
                doSendVerCodeSuccess();
                misLoading();
            }

            @Override
            public void onError(String msg) {
                txSendVerification.setEnabled(true);
                misLoading();
                ToastUtil.show(msg);
            }
        });
    }

    /**
     * 发送验证码成功执行
     */
    private void doSendVerCodeSuccess() {
        Utils.countDown(Time_Close, txSendVerification, new Utils.BaseResult() {
            @Override
            public void onStart() {
                txSendVerification.setEnabled(false);
                txSendVerification.setBackgroundResource(R.drawable.bg_cancel_gray_deep);
                txSendVerification.setTextColor(ContextCompat.getColor(getActivity(), R.color.white));
            }

            @Override
            public void onResult(Boolean t) {
                if(txSendVerification==null)return;
                txSendVerification.setEnabled(true);
                txSendVerification.setBackgroundResource(R.drawable.bg_cancel_theme);
                txSendVerification.setText("获取验证码");
                txSendVerification.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color_black));
            }
        });
    }

    /**
     * 验证验证码
     */
    private void testVerCode() {
        if(isFromByPerson){
            //手机长度及验证
            if (TextUtils.isEmpty(phoneNum)) {
                ToastUtil.show(HINT_Tel_Null_ERROR);
                return;
            }
            if ( phoneNum.length() < 11) {
                ToastUtil.show(HINT_TEL_ERROR);
                return;
            }
        }else {
            //手机长度及验证
            if (TextUtils.isEmpty(phoneNum)) {
                ToastUtil.show(HINT_Company_Account_Null_ERROR);
                return;
            }
            if ( phoneNum.length() < 8) {
                ToastUtil.show(HINT_Company_Account_ERROR);
                return;
            }
        }
        //验证码
        if (TextUtils.isEmpty(code) ){
            ToastUtil.show(HINT_CODE_Null);
            return;
        }
        if(code.length() < 6) {
            ToastUtil.show(HINT_CODE_ERROR);
            return;
        }
        if (loadingDialog == null) loadingDialog = LoadingDialog.createDialog(getActivity());
        loadingDialog.show();
        enqueue(createCallService(LoginService.class).testVerification(phoneNum, code), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                loadingDialog.cancel();
                in = new Intent(getActivity(), ModifyPwdActivity.class);
                in.putExtra("tel", phoneNum);
                in.putExtra("code", code);
                in.putExtra("isFromByPerson", isFromByPerson);
                startActivity(in);
            }

            @Override
            public void onError(String msg) {
                ToastUtil.show(msg);
                loadingDialog.cancel();
            }
        });
    }

}
